package com.cn.wanxi.common;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;



public class MyHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        /* 允许跨域的主机地址 */
        resp.setHeader("Access-Control-Allow-Origin", "http://localhost:8088");
        /* 允许跨域的请求方法GET, POST, HEAD 等 */
        resp.setHeader("Access-Control-Allow-Methods", "*");
        /* 重新预检验跨域的缓存时间 (s) */
        resp.setHeader("Access-Control-Max-Age", "3600");
        /* 允许跨域的请求头 */
        resp.setHeader("Access-Control-Allow-Headers", "*");
        /* 是否携带cookie */
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setContentType("");
//        首先登录和注册页面不能进行拦截，只能拦截后台访问的地址
        String path = req.getServletPath();
        System.out.println(path);
        //之拦截后台"/back/"开头的
        if (path.startsWith("/back/")) {
            HttpSession session = req.getSession();
            String key = req.getParameter("loginUsername");
            String username = (String) session.getAttribute(key);
            if (username == null) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("result", "noLogin");
                resp.getWriter().println(jsonObject);//            resp.sendRedirect("/html/login.html");//重定向
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
